﻿///***************************************************************
/// 시  스  템 : Updms.Cfg
/// 단위시스템 : CFG
/// 계      층 : Presentation Layer
/// 프로그램명 : Cfg1014m
/// 파  일  명 : Cfg1014m.aspx.cs
/// 설      명 : 첨부파일 정리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2010-10-15 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.SMGridView;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;

using Updms.Com.Exe;
using Updms.Cfg.Exe;


namespace Updms.Cfg
{
	public partial class Cfg1014m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Cfg1014m";
		public static readonly string gs_path_info = "/updms/Cfg/" + PID + ".aspx";

		Global global = new Global();
		
		//메뉴 선택값
		protected string gs_sm = "";

		// 페이지모드
		private string gs_page_mode = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript

		private void SetClientScript()
		{
			//onKeyUp이벤트
			//txt_XXX.Attributes.Add("onkeyup", "document.form1.txt_limit_use.value=addComma(document.form1.txt_txt_XXX.value);");
		}

		#endregion

		#region SetInit, SetSearchParameter

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			// Source
		}


		#endregion

		#region 리스트 (GetDbFileList, GetDbFileMultiList, SearchProcess)

		//조회
		private void GetDbFileList(DataTable dt)
		{
			//DB - 실제파일 비교
			string ls_attach_file_path = FILE_PATH_UPLOAD;

			int cnt = dt.Rows.Count;
			lbl_result_count.Text = cnt.ToString("#,###,##0");

			if (dt.Rows.Count > 0)
			{
				DataColumn dc = new DataColumn("Exist_Local", typeof(string));
				dt.Columns.Add(dc);

				for (int i = 0; i < cnt; i++)
				{
					string ls_attach_file = DataTableUtil.GetFldStr(dt, i, "Attach_File_Nm");
					string ls_file_path = ls_attach_file_path + ls_attach_file;

					dt.Rows[i]["Exist_Local"] = FileUtil.IsFileExist(ls_file_path) ? "Y" : "N";
				}

				//정렬
				DataView dv = dt.DefaultView;
				dv.Sort = "Attach_File_Nm";
				dt = dv.ToTable();

				GridView1.DataSource = dt;
				GridView1.DataBind();

				//로컬파일 대비 체크
				GetLocalFileList(dt);
			}
		}

		//DB파일 - 멀티
		private void GetDbFileMultiList(DataTable dt)
		{
			//DB - 실제파일 비교
			string ls_attach_file_path = FILE_PATH_UPLOAD;

			int cnt = dt.Rows.Count;
			lbl_result_count_db_multi.Text = cnt.ToString("#,###,##0");

			if (dt.Rows.Count > 0)
			{
				DataColumn dc = new DataColumn("Exist_Local", typeof(string));
				dt.Columns.Add(dc);

				for (int i = 0; i < dt.Rows.Count; i++)
				{
					string ls_attach_file = DataTableUtil.GetFldStr(dt, i, "Attach_File_Nm");
					string ls_file_dir = DataTableUtil.GetFldStr(dt, i, "File_Dir");
					string ls_file_path = ls_attach_file_path + ls_file_dir + "\\" + ls_attach_file;

					dt.Rows[i]["Exist_Local"] = FileUtil.IsFileExist(ls_file_path) ? "Y" : "N";
				}

				//정렬
				DataView dv = dt.DefaultView;
				dv.Sort = "File_Dir, Attach_File_Nm";
				dt = dv.ToTable();

				GridView3.DataSource = dt;
				GridView3.DataBind();

				//로컬파일 대비 체크
				GetLocalFileMultiList(dt);
			}
		}

		//검색
		private void SearchProcess()
		{
			gs_page_mode = "R";
			
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Cfg1014m_NT _Cfg1014m_NT = new Cfg1014m_NT())
			{
				lo_ds.Merge(_Cfg1014m_NT.GetAttachFileList(lo_dp));
			}

			if (lo_ds.Tables.Count > 1)
			{
				GetDbFileList(lo_ds.Tables[0]);
				GetDbFileMultiList(lo_ds.Tables[1]);
			}

			//일치여부
			if (lbl_result_count.Text != lbl_result_count_local.Text ||	lbl_result_count_db_multi.Text != lbl_result_count_local_multi.Text)
			{
				CallMsgBoxInAjax("MSG_ERR_207"); //일치하지 않는 파일이 존재합니다
			}
		}

		#endregion

		#region 로컬파일목록 조회 (GetLocalFileList, GetLocalFileMultiList)

		//로컬파일 확인
		private void GetLocalFileList(DataTable dt)
		{
			DataTable lo_dt = new DataTable();
			string ls_rslt = String.Empty;
			
			//DataTable에 DataColumn추가후 GridView1에 바인딩
			DataColumn dc1 = new DataColumn("Attach_File_Nm", typeof(string));
			lo_dt.Columns.Add(dc1);

			//DataTable에 DataColumn추가후 GridView1에 바인딩
			DataColumn dc2 = new DataColumn("Exist_Yn", typeof(string));
			lo_dt.Columns.Add(dc2);

			string[] la_local_files = Directory.GetFiles(Server.MapPath("../Common/Upload/"), "*.*");

			lbl_result_count_local.Text = la_local_files.Length.ToString("#,###,##0");

			if (la_local_files.Length > 0)
			{
				for (int i = 0; i < la_local_files.Length; i++)
				{
					FileInfo fi = new FileInfo(la_local_files[i]);
					string ls_local_file = fi.Name;

					DataRow dr = lo_dt.NewRow();
					dr["Attach_File_Nm"] = ls_local_file;

					string ls_exist_file = "N";

					//파일이 DB에 있는지 여부 체크
					for (int j = 0; j < dt.Rows.Count; j++)
					{
						string ls_db_file = dt.Rows[j]["Attach_File_Nm"].ToString();

						if (ls_local_file == ls_db_file)
						{
							ls_exist_file = "Y";
						}
					}

					dr["Exist_Yn"] = ls_exist_file;
					
					lo_dt.Rows.Add(dr);
				}

				//정렬
				DataView dv = lo_dt.DefaultView;
				dv.Sort = "Attach_File_Nm";
				lo_dt = dv.ToTable();

				GridView2.DataSource = lo_dt;
				GridView2.DataBind();
			}
		}

		//로컬파일 확인 - 멀티
		private void GetLocalFileMultiList(DataTable dt)
		{
			DataTable lo_dt = new DataTable();
			string ls_rslt = String.Empty;

			//DataTable에 DataColumn추가후 GridView에 바인딩
			DataColumn dc1 = new DataColumn("File_Dir", typeof(string));
			lo_dt.Columns.Add(dc1);

			DataColumn dc2 = new DataColumn("Attach_File_Nm", typeof(string));
			lo_dt.Columns.Add(dc2);

			DataColumn dc3 = new DataColumn("Exist_Yn", typeof(string));
			lo_dt.Columns.Add(dc3);

			//Upload 하위폴더 목록을 가져온다.
			string[] la_local_dirs = Directory.GetDirectories(Server.MapPath("../Common/Upload/"), "*.*");

			//하위폴더 목록만큼 roop돌면서 파일목록을 가져온다.
			//하위폴더명은 File_Dir에 지정한다.
			int li_total_local_cnt = 0;
			for (int i = 0; i < la_local_dirs.Length; i++)
			{
				string ls_local_file_dir = Path.GetFileName(la_local_dirs[i]); //Upload하위의 폴더명
				string[] la_local_files = Directory.GetFiles(Server.MapPath("../Common/Upload/" + ls_local_file_dir), "*.*");

				if (la_local_files.Length > 0)
				{
					for (int j = 0; j < la_local_files.Length; j++)
					{
						FileInfo fi = new FileInfo(la_local_files[j]);
						string ls_local_file_nm = fi.Name;

						DataRow dr = lo_dt.NewRow();
						dr["File_Dir"] = ls_local_file_dir;
						dr["Attach_File_Nm"] = ls_local_file_nm;

						string ls_exist_file = "N";

						//동일한 경로에 파일이 DB에 있는지 여부 체크
						for (int k = 0; k < dt.Rows.Count; k++)
						{
							string ls_db_file_dir = dt.Rows[k]["File_Dir"].ToString();
							string ls_db_file_nm = dt.Rows[k]["Attach_File_Nm"].ToString();

							if (ls_db_file_dir == ls_local_file_dir && ls_local_file_nm == ls_db_file_nm)
							{
								ls_exist_file = "Y";
							}
						}

						dr["Exist_Yn"] = ls_exist_file;

						lo_dt.Rows.Add(dr);

						li_total_local_cnt++;
					}

					//정렬
					DataView dv = lo_dt.DefaultView;
					dv.Sort = "File_Dir, Attach_File_Nm";
					lo_dt = dv.ToTable();

					GridView4.DataSource = lo_dt;
					GridView4.DataBind();
				}
			}

			lbl_result_count_local_multi.Text = li_total_local_cnt.ToString("#,###,##0");
		}
		
		#endregion

		#region 데이터(DB) 정리 (CleanDbAttachFile, CleanDbAttachFileMulti)

		//DB기준
		private void CleanDbAttachFile(string ls_xml)
		{
			try
			{
				using (Cfg1014m_RT _Cfg1014m_RT = new Cfg1014m_RT())
				{
					int li_return = _Cfg1014m_RT.CleanAttachFile(ls_xml);
					string ls_msg_id = (li_return > 0) ? "MSG_INF_017" : "MSG_ERR_155";	//정리되었습니다:정리할 수 없습니다
					CallMsgBoxInAjax(ls_msg_id);

					SearchProcess();
				}
			}
			catch (Exception ex)
			{
				CallExceptionMsgBoxInAjax(ex);
			}
		}

		//DB기준 - 멀티
		private void CleanDbAttachFileMulti(string ls_xml)
		{
			try
			{
				using (Com9010m_RT _Com9010m_RT = new Com9010m_RT())
				{
					int li_return = _Com9010m_RT.DeleteByFileId(ls_xml);
					string ls_msg_id = (li_return > 0) ? "MSG_INF_017" : "MSG_ERR_155";	//정리되었습니다:정리할 수 없습니다
					CallMsgBoxInAjax(ls_msg_id);

					SearchProcess();
				}
			}
			catch (Exception ex)
			{
				CallExceptionMsgBoxInAjax(ex);
			}
		}
		
		#endregion

		#region 데이터(LOCAL) 정리 (CleanLocalAttachFile, CleanLocalAttachFileMulti)

		//정리 - LOCAL
		private void CleanLocalAttachFile()
		{
			try
			{
				for (int i = 0; i < GridView2.Rows.Count; i++)
				{
					GridViewRow row = GridView2.Rows[i];
					HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check_local");

					string ls_file_name = FILE_PATH_UPLOAD + GridView2.Rows[i].Cells[1].Text;

					if (cb.Checked)
					{
						//파일삭제
						if (FileUtil.IsFileExist(ls_file_name))
						{
							File.Delete(ls_file_name);
						}
					}
				}
			}
			catch (Exception ex)
			{
				CallMsgBoxInAjax(ex.ToString());
			}

			CallMsgBoxInAjax("MSG_INF_017");	//정리되었습니다
			SearchProcess();
		}

		//정리 - LOCAL 멀티
		private void CleanLocalAttachFileMulti()
		{
			try
			{
				for (int i = 0; i < GridView4.Rows.Count; i++)
				{
					GridViewRow row = GridView4.Rows[i];
					HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check_local_multi");

					string ls_file_name = FILE_PATH_UPLOAD + GridView4.Rows[i].Cells[1].Text + "\\" + GridView4.Rows[i].Cells[2].Text;

					if (cb.Checked)
					{
						//파일삭제
						if (FileUtil.IsFileExist(ls_file_name))
						{
							File.Delete(ls_file_name);
						}
					}
				}
			}
			catch (Exception ex)
			{
				CallMsgBoxInAjax(ex.ToString());
			}

			CallMsgBoxInAjax("MSG_INF_017");	//정리되었습니다
			SearchProcess();
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			switch (gs_page_mode)
			{
				case "":	// 처음 페이지로드시
					table_list_set.Visible = false;
					break;
				case "R":	// 검색버튼 클릭시
					table_list_set.Visible = true;
					break;
			}

			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//DB기준
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				string ls_exist_local_yn = e.Row.Cells[8].Text;

				HtmlInputCheckBox cb_check = (HtmlInputCheckBox)e.Row.Cells[0].FindControl("cb_check_db");
				
				cb_check.Disabled = ls_exist_local_yn.Equals("Y");	//정보가 같으면 비활성화
				cb_check.Checked = ls_exist_local_yn.Equals("N");	//정보가 다르면 체크

				e.Row.Cells[8].Attributes.Add("class", ls_exist_local_yn.Equals("Y") ? "" : "bg_peach color_red");
			}
			//머지
			SMGridView sGv = new SMGridView(this.Page, ref GridView1);
			sGv.RowSpanGridView(GridView1, 5);
		}

		//LOCAL기준
		protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				string ls_exist_local_yn = e.Row.Cells[2].Text;

				HtmlInputCheckBox cb_check = (HtmlInputCheckBox)e.Row.Cells[0].FindControl("cb_check_local");

				cb_check.Disabled = ls_exist_local_yn.Equals("Y");	//정보가 같으면 비활성화
				cb_check.Checked = ls_exist_local_yn.Equals("N");	//정보가 다르면 체크	

				e.Row.Cells[2].Attributes.Add("class", ls_exist_local_yn.Equals("Y") ? "" : "bg_peach color_red");
			}
		}

		//DB기준 - 멀티
		protected void GridView3_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				string ls_exist_local_yn = e.Row.Cells[5].Text;

				HtmlInputCheckBox cb_check = (HtmlInputCheckBox)e.Row.Cells[0].FindControl("cb_check_db_multi");

				cb_check.Disabled = ls_exist_local_yn.Equals("Y");	//정보가 같으면 비활성화
				cb_check.Checked = ls_exist_local_yn.Equals("N");	//정보가 다르면 체크	

				e.Row.Cells[5].Attributes.Add("class", ls_exist_local_yn.Equals("Y") ? "" : "bg_peach color_red");
			}

			//머지
			SMGridView sGv = new SMGridView(this.Page, ref GridView3);
			sGv.RowSpanGridView(GridView3, 1);
			sGv.RowSpanGridView(GridView3, 2);
		}

		//LOCAL기준 - 멀티
		protected void GridView4_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				string ls_exist_local_yn = e.Row.Cells[3].Text;

				HtmlInputCheckBox cb_check = (HtmlInputCheckBox)e.Row.Cells[0].FindControl("cb_check_local_multi");

				cb_check.Disabled = ls_exist_local_yn.Equals("Y");	//정보가 같으면 비활성화
				cb_check.Checked = ls_exist_local_yn.Equals("N");	//정보가 다르면 체크	

				e.Row.Cells[3].Attributes.Add("class", ls_exist_local_yn.Equals("Y") ? "" : "bg_peach color_red");
			}

			//머지
			SMGridView sGv = new SMGridView(this.Page, ref GridView4);
			sGv.RowSpanGridView(GridView4, 1);
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//정리 - DB
		protected void ibtn_clean_db_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");

			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check_db");

				if (cb.Checked)
				{
					string ls_seq = GridView1.DataKeys[i].Values["Seq"].ToString();
					string ls_table_nm = GridView1.DataKeys[i].Values["Table_Nm"].ToString();
					string ls_column_nm = GridView1.DataKeys[i].Values["Column_Nm"].ToString();

					sb.Append("<UPDMS_CFG_ATTACH_FILE>");
					sb.Append("<Table>" + ls_table_nm + "</Table>");
					sb.Append("<Column>" + ls_column_nm + "</Column>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("</UPDMS_CFG_ATTACH_FILE>");
				}
			}
			sb.Append("</UPDMS>");

			CleanDbAttachFile(sb.ToString());
		}

		//정리 - LOCAL
		protected void ibtn_clean_local_Click(object sender, EventArgs e)
		{
			CleanLocalAttachFile();
		}

		//정리 - DB 멀티
		protected void ibtn_clean_db_multi_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");

			for (int i = 0; i < GridView3.Rows.Count; i++)
			{
				GridViewRow row = GridView3.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check_db_multi");

				if (cb.Checked)
				{
					string ls_file_id = GridView3.DataKeys[i].Values["File_Id"].ToString();

					sb.Append("<UPDMS_COM_FILE>");
					sb.Append("<File_Id>" + ls_file_id + "</File_Id>");
					sb.Append("</UPDMS_COM_FILE>");
				}
			}
			sb.Append("</UPDMS>");

			CleanDbAttachFileMulti(sb.ToString());
		}

		//정리 - LOCAL 멀티
		protected void ibtn_clean_local_multi_Click(object sender, EventArgs e)
		{
			CleanLocalAttachFileMulti();
		}
		
		#endregion

	}
}
